<template>
  <CommonDialog v-model="dialogFlag" :title="props.dialogTitle" :confirm="handleConfirm" @closed="closedDialog">
    <div class="dialog-content">
      <el-form ref="myFormRef" :model="params" label-position="right" label-width="auto" :rules="myFormRules">
        <el-form-item label="姓名：" prop="name">
          <CommonInput v-model="params.name" placeholder="请输入姓名" :maxlength="50" width="400px" />
        </el-form-item>
        <el-form-item label="性别：" prop="gender">
          <CommonSelect v-model="params.gender" :options="dropStore.gender" width="400px" />
        </el-form-item>
      </el-form>
    </div>
  </CommonDialog>
</template>
<script lang="ts" setup>
import CommonDialog from '@/components/dialog/CommonDialog.vue'
import CommonInput from '@/components/input/CommonInput.vue'
import CommonSelect from '@/components/select/CommonSelect.vue'
import { ref, type PropType } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useDropStore } from '@/store/modules/drop'
export interface ParamsVo {
  id?: number | null;
  name: string;
  gender: string;
}

const dropStore = useDropStore()

const props = defineProps({
  confirm: {
    type: Function as PropType<(params: ParamsVo) => Promise<void>>,
    default: () => Promise.resolve()
  },
  dialogTitle: {
    type: String,
    default: ''
  }
})

const dialogFlag = ref(false)
const myFormRef = ref<FormInstance>()
const params = ref<ParamsVo>({
  id: null,
  name: '',
  gender: 'MYSQL'
})
const myFormRules = ref<FormRules>({
  // typeName: [
  //   { required: true, message: '请输入品类名称', trigger: 'change' },
  //   { pattern: /^[\u4E00-\u9FA5A-Za-z\d]+$/, message: '品类名称不能输入特殊字符', trigger: 'change' }
  // ],
  name: [
    { required: true, message: '请输入名称', trigger: 'change' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
})

// 确定新增、编辑
const handleConfirm = async () => {
  await myFormRef.value?.validate(async (valid, fields) => {
    if (valid) {
      await props.confirm(params.value)
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 清空form表单信息， 然后关闭弹窗
const closedDialog = () => {
  params.value = {
    id: null,
    name: '',
    gender: ''
  }
  myFormRef.value?.resetFields() // 编辑时，本代码不能清空默认的赋值，故增加上方代码，手动默认赋值
  dialogFlag.value = false
}

defineExpose({
  dialogFlag,
  params,
  closedDialog
})
</script>
<style lang="scss" scoped>
.dialog-content {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
